package Pre;

import java.io.*;
import java.nio.file.Files;
import java.util.Date;

public class CopyFile {
    public static void main(String[] args) {
        File targe = new File("E:\\IO流练习\\InoutStream\\001\\002.txt");
        File dest = new File("E:\\IO流练习\\InoutStream\\copy");
        String name = targe.getName();
        //获取时间戳来存储文件
//        String destName = new Date().getTime() + name.substring(name.lastIndexOf('.'));
        String destName = 4 + name.substring(name.lastIndexOf('.'));
        File destFile = new File(dest + File.separator + destName);
        copy4(targe,destFile);
    }
    private static void copy1(File target,File dest){
        if (!dest.getParentFile().exists()) { // 判断父级目录是否存在不存在创建父级目录
            dest.getParentFile().mkdirs();
        }
        try ( FileInputStream in = new FileInputStream(target);
              FileOutputStream out = new FileOutputStream(dest);){
            byte[] all =in.readAllBytes();
            out.write(all);
            out.flush();;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private static void copy2 (File target,File dest){
        try {
            Files.copy(target.toPath(), dest.toPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //long   transferTo(Writer out)
    //从此读取器读取所有字符，并将字符写入 按照阅读顺序给定作者。
    private static void copy3(File target,File dest){
        try ( FileInputStream in = new FileInputStream(target);
              FileOutputStream out = new FileOutputStream(dest);){
            in.transferTo(out);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private static void copy4(File target,File dest){
        try ( FileInputStream in = new FileInputStream(target);
              FileOutputStream out = new FileOutputStream(dest);){
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
